local S = minetest.get_translator("advtrains_vactrain")

local vacuum_range = tonumber(minetest.settings:get("vactrain_range")) or 3
local max_working_speed = tonumber(minetest.settings:get("vactrain_max_speed")) or 2


function round_down(pos)
   return {x=pos.x, y=math.floor(pos.y), z=pos.z}
end

local function vacuum(pos, radius, inv)
	for _, object in ipairs(minetest.get_objects_inside_radius(pos, vacuum_range)) do
		local luaentity = object:get_luaentity()
		if not object:is_player() and luaentity and luaentity.name == "__builtin:item" and luaentity.itemstring ~= "" then
			if inv and inv:room_for_item("box", ItemStack(luaentity.itemstring)) then
				inv:add_item("box", ItemStack(luaentity.itemstring))
				luaentity.itemstring = ""
				object:remove()
			end
		end
	end
end

advtrains.register_wagon("advtrains_wagon_vac", {
	mesh = "moretrains_wagon_box.b3d",
	textures = {"vactrain_wagon.png"},
	seats = {},
	drives_on = {default=true},
	max_speed = 10,
	visual_size = {x=1,y=1},
	wagon_span = 2.672,
	collisionbox = {-1.0,-0.5,-1.0, 1.0,2.5,1.0},
	drops = {"default:steelblock","pipeworks:sand_tube_1"},
	has_inventory = true,
	get_inventory = function (self) return minetest.get_inventory({type="detached", name="advtrains_wgn_"..self.id}) end,
	get_inventory_formspec = function(self, pname, invname)
		local data = advtrains.wagons[self.id]
		local prop = ""
		if data.owner==pname then
			prop = "button_exit[0,4;4,1;prop;"..S("Wagon properties").."]"
		end
		return "size[8,11]"..
			"list["..invname..";box;0,0;8,4;]"..
			"list[current_player;main;0,7;8,4;]"..
			"listring[]"..prop
	end,
	inventory_list_sizes = {
		box=8*4,
	},
	custom_on_step = function(self,dtime)
		--Reduce lag: don't run if stationary or in transit
		if (self:train().velocity == 0 or self:train().velocity > max_working_speed) then
			return
		end
		local pos = vector.round(round_down(self.object:getpos()))
		local inv = minetest.get_inventory({type="detached", name="advtrains_wgn_"..self.id})
		
		vacuum(pos,vacuum_range,inv)
	end,
}, S("Vacuum Wagon"), "vactrain_wagon_inv.png")

minetest.register_craft({
	output = "advtrains:advtrains_wagon_vac",
	recipe = {
		{"pipeworks:sand_tube_1","technic:motor","pipeworks:sand_tube_1"},
		{"","advtrains:moretrains_wagon_box",""}
	},
})

print("VacTrain loaded")